/**
 * 生成以指定点为中心的随机地形块
 * 
 * @param {Object} world - 世界地图对象，包含所有已生成的地块信息
 * @param {number} centerX - 中心点的X坐标
 * @param {number} centerY - 中心点的Y坐标
 * @returns {void} 无返回值，直接修改传入的world对象
 */
export function generateTerrain(world, centerX, centerY) {
    const tileSize = 50;
    const generateRange = 1500;
    const obstacleDensity = 0.1;
    const maxTiles = 5000; // 新增：最大地形块数量限制

    // 如果地形块过多，清理最旧的部分
    if (world.tiles.length > maxTiles) {
        world.tiles.splice(0, world.tiles.length - maxTiles);
    }

    // 初始化二维数组来存储地形块
    if (!world.tileMap) {
        world.tileMap = {};
    }

    // 计算需要生成的区域范围
    const minX = Math.floor((centerX - generateRange) / tileSize) * tileSize;
    const maxX = Math.floor((centerX + generateRange) / tileSize) * tileSize;
    const minY = Math.floor((centerY - generateRange) / tileSize) * tileSize;
    const maxY = Math.floor((centerY + generateRange) / tileSize) * tileSize;

    // 生成当前区域内的障碍物（仅生成一次）
    for (let x = minX; x <= maxX; x += tileSize) {
        for (let y = minY; y <= maxY; y += tileSize) {
            // 检查是否已经生成过该位置
            const exists = world.tileMap[x] && world.tileMap[x][y];
            if (!exists) {
                // 根据概率决定是否生成障碍物
                if (Math.random() < obstacleDensity) {
                    const tile = {
                        x: x,
                        y: y,
                        width: tileSize,
                        height: tileSize,
                        type: Math.random() > 0.5 ? 'wall' : 'tree',
                        shape: Math.random() > 0.5 ? 'rect' : 'circle', // 随机形状
                        color: `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)})` // 随机颜色
                    };
                    if (!world.tileMap[x]) {
                        world.tileMap[x] = {};
                    }
                    world.tileMap[x][y] = tile;
                    world.tiles.push(tile);
                } else {
                    // 标记该位置已经处理过
                    if (!world.tileMap[x]) {
                        world.tileMap[x] = {};
                    }
                    world.tileMap[x][y] = {
                        x: x,
                        y: y,
                        width: tileSize,
                        height: tileSize,
                        type: 'empty'
                    };
                }
            }
        }
    }
}

export function renderTerrain(Game, canvas, ctx) {
    // 获取相机可视范围
    const visibleLeft = Game.camera.x;
    const visibleRight = Game.camera.x + canvas.width;
    const visibleTop = Game.camera.y;
    const visibleBottom = Game.camera.y + canvas.height;

    // 计算可视范围内的最小和最大坐标
    const minX = Math.floor(visibleLeft / 50) * 50;
    const maxX = Math.floor(visibleRight / 50) * 50;
    const minY = Math.floor(visibleTop / 50) * 50;
    const maxY = Math.floor(visibleBottom / 50) * 50;

    // 渲染可视范围内的地形块
    for (let x = minX; x <= maxX; x += 50) {
        for (let y = minY; y <= maxY; y += 50) {
            const tile = Game.world.tileMap[x] && Game.world.tileMap[x][y];
            if (tile && tile.type !== 'empty') {
                const screenX = tile.x - Game.camera.x;
                const screenY = tile.y - Game.camera.y;
                if (screenX > -tile.width && screenX < canvas.width &&
                    screenY > -tile.height && screenY < canvas.height) {
                    // 设置颜色
                    ctx.fillStyle = tile.color || (tile.type === 'wall' ? '#666' : '#228B22');
                    ctx.beginPath();
                    // 根据形状绘制
                    if (tile.shape === 'circle') {
                        ctx.arc(
                            screenX + tile.width / 2,
                            screenY + tile.height / 2,
                            Math.min(tile.width, tile.height) / 2,
                            0,
                            Math.PI * 2
                        );
                    } else {
                        ctx.rect(
                            screenX,
                            screenY,
                            tile.width,
                            tile.height
                        );
                    }
                    ctx.fill();
                }
            }
        }
    }
}
